<?php
class fs_save extends CI_Model {

    /* Prepare vars */
    var $incoming_data = array();
    var $valid_field = array();
    var $valid_data = array();
    var $db_fields = array();
    var $_db = "";
    var $_table = "";
    var $_id = 0;

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();

        $this->load->model("fs_tables");
        $this->load->helper('array');
    }

    public function save_data($post)
    {
        // Set incoming data
        $this->incoming_data = $post;
        $this->_db = $this->session->userdata('active_site');
        $this->_table = $this->session->userdata('form_post_table');
        $this->_id = $this->session->userdata('form_post_id');

        // Set valid fields
        $this->valid_field = $this->get_valid_tablefields();

        // Set valid data
        $this->valid_data = $this->get_valid_data();

        /* Debugging
            print_r ($this->valid_field);
            echo "\n\n";
            print_r($this->valid_data);
        */

        // Save data
        try {
            $this->save();
            $msg = array('success' => 1, 'msg' => "The data has been saved to the database.");
            echo json_encode($msg);
        } catch (Exception $e) {
            //echo 'Caught exception: ',  $e->getMessage(), "\n";
            $msg = array('success' => 0, 'msg' => "There was a problem saving the data, please contact your system administrator.");
            echo json_encode($msg);
        }

    }

    private function save()
    {
        // Init active record class
        $dbtmp = $this->fs_tables->select_single_db();

        // Insert or update
        if($this->_id > 0) {
            // Update
            $dbtmp->where('id', $this->_id);
            $dbtmp->update($this->_table, $this->valid_data);
        } else {
            // Insert
            $dbtmp->insert($this->_table, $this->valid_data);
        }

        //echo $dbtmp->affected_rows();
    }
    
    // Get fields from db
    private function get_valid_tablefields()
    {
        // Get fields from database
        $query = $this->db->query("SHOW FULL COLUMNS FROM " . $this->db->escape_str($this->_table) . " FROM " . $this->_db);
        return $query->result_array();
    }

    private function get_valid_data()
    {
        $raw_data = $this->incoming_data;
        $valid_fields = $this->valid_field;
        $valid_data = array();

        // Valid fields
        foreach ($valid_fields as $field)
        {
            $field_type = (strpos($field["Type"], "(") > 0) ? substr($field["Type"], 0, strpos($field["Type"],"(") ) : $field["Type"];
            $field_maxlength =  ( strpos($field["Type"], "(") > 0) ? substr( $field["Type"], strpos($field["Type"], "(")+1, strlen($field["Type"]) ) : "";
            $field_maxlength = str_replace(")", "", $field_maxlength);
            $input_from_form = element($field['Field'], $raw_data);

            // We got some special fields that we need to take care off
            switch ($field_type) {
                case "int":
                    // Leave from results in case of auto_increment
                    if($field['Extra'] != 'auto_increment') {
                        $valid_data[$field['Field']] = $input_from_form;
                    }
                    break;
                case "tinyint":
                        $valid_data[$field['Field']] = ($input_from_form == "on") ? 1 : 0;
                    break;
                case "datetime":
                case "timestamp":
                    // We break up datetime and timestamps in the form view so
                    // we have to put them back together
                    $valid_data[$field['Field']] = $this->glue_fields($field, $field_type);
                    break;
                case "date":
                    $valid_data[$field['Field']] = date('Y-m-d', strtotime($input_from_form));
                    break;
                default:
                    $valid_data[$field['Field']] = $input_from_form;
                    break;
            }
        }

        return $valid_data;
    }


    private function glue_fields($field, $type)
    {
        // Standard values
        $name = $field["Field"];
        $value = $this->input->post($field["Field"]."_fs_split_date") . " " . $this->input->post($field["Field"]."_fs_split_time");
        
        // We got some special fields that we need to take care off
        switch ($type) {
            case "datetime":
                $value = date('Y-m-d H:i:s', strtotime($value));
                break;
            case "timestamp":
                $value = date('Y-m-d H:i:s', strtotime($value));
                break;
        }

        return $value;
    }

}